#pragma once
#include <functional>
#include <string>
#include "UdpSocket.hpp"
#include "InetAddr.hpp"

namespace UdpChatServerModule
{
    using namespace UdpSocketModule;
    using namespace InetAddrModule;
    using handler = std::function<void(UdpSocket&,const std::string&, InetAddr&)>;
    class UdpChatServer
    {
    public:
        UdpChatServer(handler func, std::string ip = "0.0.0.0", uint16_t port = defaultport)
         : _port(port)
         , _chatfunc(func)
        {
            _socket.Bind(ip, port);
        }

        void Start()
        {
            while (true)
            {
                std::string msg;
                uint16_t client_port;
                std::string client_ip;
                _socket.Recvfrom(&msg, &client_port, &client_ip);
                InetAddr client(client_port, client_ip);
                _chatfunc(_socket, msg, client);
            }
        }

    private:
        UdpSocket _socket;
        uint16_t _port;
        handler _chatfunc;
    };
}